<template>
    <div>
        <!-- 面包屑导航视图 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card class="box-card">
            <!-- 警告提示 -->
            <el-alert title="注意：只允许为第三级设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
            <!-- 选择分类 -->
            <el-row>
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 选择商品分类的级联选择框 -->
                    <el-cascader :options="catelist" v-model="selectedOptions" :props="cascaderProps" @change="handleChange"
                        clearable>
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tab页签区域 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 添加动态参数面板 -->
                <el-tab-pane label="动态参数" name="many">
                    <template>
                        <el-button type="primary" size="mini" :disabled="isButtonDisabled"
                            @click="addAttrDialogVisible = true">添加参数</el-button>
                        <!-- 动态参数表格 -->
                        <el-table :data="manyTableData" border stripe>
                            <!-- 展开列 -->
                            <el-table-column type="expand">
                                <template v-slot="scope">
                                    <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable
                                        @close="handleColose(scope.row, index)">{{ item
                                        }}</el-tag>
                                    <!-- 输入文本框 -->
                                    <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)">
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                        New
                                        Tag</el-button>
                                </template>
                            </el-table-column>
                            <!-- 索引列 -->
                            <el-table-column type="index" label="#"></el-table-column>
                            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                            <el-table-column label="操作">
                                <template v-slot="scope">
                                    <el-button size="mini" type="primary" icon="el-icon-edit"
                                        @click="showEdit(scope.row)">编辑</el-button>
                                    <el-button size="mini" type="danger" icon="el-icon-delete"
                                        @click="removeParams(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-tab-pane>
                <!-- 添加静态属性面板 -->
                <el-tab-pane label="静态属性" name="only">
                    <template>
                        <el-button type="primary" size="mini" :disabled="isButtonDisabled"
                            @click="addAttrDialogVisible = true">添加属性</el-button>
                        <!-- 静态属性表格 -->
                        <el-table :data="onlyTableData" border stripe>
                            <!-- 展开列 -->
                            <el-table-column type="expand">
                                <template v-slot="scope">
                                    <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable
                                        @close="handleColose(scope.row, index)">{{ item
                                        }}</el-tag>
                                    <!-- 输入文本框 -->
                                    <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)">
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                        New
                                        Tag</el-button>
                                </template>
                            </el-table-column>
                            <!-- 索引列 -->
                            <el-table-column type="index" label="#"></el-table-column>
                            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                            <el-table-column label="操作">
                                <template v-slot="scope">
                                    <el-button size="mini" type="primary" icon="el-icon-edit"
                                        @click="showEdit(scope.row)">编辑</el-button>
                                    <el-button size="mini" type="danger" icon="el-icon-delete"
                                        @click="removeParams(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加动态参数和静态属性对话框 -->
        <el-dialog :title="'添加' + isTitle" :visible.sync="addAttrDialogVisible" width="50%" @close="addAttrDialogClosed">
            <el-form :model="addAttrForm" :rules="rules" ref="addAttrRef" label-width="120px" class="demo-ruleForm">
                <el-form-item :label="isTitle" prop="attr_name">
                    <el-input v-model="addAttrForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addAttrDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addAttr">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改参数对话框 -->
        <el-dialog :title="'修改' + isTitle" :visible.sync="editAttrDialogVisible" width="50%" @close="editAttrDialogClosed">
            <el-form :model="editAttrForm" :rules="rules" ref="editAttrRef" label-width="120px" class="demo-ruleForm">
                <el-form-item :label="isTitle" prop="attr_name">
                    <el-input v-model="editAttrForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editAttrDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editAttr">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

export default {
    name: 'Params',
    data() {
        return {
            // 商品分类的数据列表，默认为空
            catelist: [],
            // 级联选择器配置选项
            //  指定级联选择器的配置对象
            cascaderProps: {
                value: 'cat_id',
                label: 'cat_name',
                children: 'children',
                expandTrigger: 'hover'
            },
            // 级联选择框双向绑定数组
            selectedOptions: [],
            // 被激活的页签名称
            activeName: 'many',
            // 动态参数数据
            manyTableData: [],
            // 静态属性数据
            onlyTableData: [],
            // 控制添加参数对话框显示与隐藏
            addAttrDialogVisible: false,
            // 控制修改参数对话框显示与隐藏
            editAttrDialogVisible: false,
            // 添加参数表单对象
            addAttrForm: {
                attr_name: ''
            },
            // 修改参数表单对象
            editAttrForm: {
                attr_id: null,
                attr_name: '',
                cat_id: null,
                attr_vals: ''
            },
            // 表单验证
            rules: {
                attr_name: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' }
                ],
            }
        }
    },
    mounted() {
        this.getCateList()
    },
    computed: {
        //添加计算属性用来获取按钮禁用与否
        isButtonDisabled() {
            return this.selectedOptions.length !== 3
        },
        // 当前选中的三级分类的Id
        cateId() {
            if (this.selectedOptions.length === 3) {
                return this.selectedOptions[2]
            }
            return null
        },
        // 判断动态静态参数属性
        isTitle() {
            return this.activeName === 'many' ? '动态参数' : '静态属性'
        }
    },
    methods: {
        // 获取商品分类数据
        async getCateList() {
            const { data: res } = await this.$http.get('categories')
            if (res.meta.status !== 200) return this.$message.error('商品分类数据请求失败！')
            // console.log(res.data);
            this.catelist = res.data
        },
        // 获取参数列表数据
        async getParamsData() {
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                //控制按钮与文本框的切换显示
                this.$set(item, 'inputVisible', false)
                // 文本框输入的内容
                this.$set(item, 'inputValue', '')
            })
            // console.log(res.data);
            if (this.activeName === 'many') {
                this.manyTableData = res.data
            } else {
                this.onlyTableData = res.data
            }
        },
        // 级联选择框选中项发生变化出发事件
        handleChange(value) {
            // 证明选择中的是三级分类
            if (this.selectedOptions.length !== 3) {
                this.selectedOptions = []
                this.manyTableData = []
                this.onlyTableData = []
                return
            }
            this.getParamsData()
        },
        // 切换tab
        handleTabClick() {
            // console.log(tab, event);
            if (this.isButtonDisabled) {
                return
            }
            this.getParamsData()
        },
        // 监听添加参数对话框关闭事件
        addAttrDialogClosed() {
            this.$refs.addAttrRef.resetFields()
        },
        // 添加参数
        addAttr() {
            this.$refs.addAttrRef.validate(async valid => {
                if (!valid) return
                //发起表单添加分类请求
                const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addAttrForm.attr_name, attr_sel: this.activeName, attr_vals: "" })
                // console.log(res);
                if (res.meta.status !== 201) return this.$message.error(res.meta.msg)

                this.$message.success(res.meta.msg)
                // 隐藏添加分类的参数对话框
                this.addAttrDialogVisible = false
                // 重新请求商品分类列表数据（刷新列表）
                this.getParamsData()
            })
        },
        // 点击按钮,打开修改对话框
        async showEdit(row) {
            const { data: res } = await this.$http.get(`categories/${row.cat_id}/attributes/${row.attr_id}`, { attr_sel: this.activeName, attr_vals: "a,b,c" })
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.editAttrForm.attr_name = res.data.attr_name
            this.editAttrForm.cat_id = res.data.cat_id
            this.editAttrForm.attr_id = res.data.attr_id
            this.editAttrForm.attr_vals = res.data.attr_vals
            this.editAttrDialogVisible = true

        },
        // 监听修改参数对话框关闭事件
        editAttrDialogClosed() {
            this.$refs.editAttrRef.resetFields()
        },
        // 添加参数
        editAttr() {
            this.$refs.editAttrRef.validate(async valid => {
                if (!valid) return
                //发起表单添加分类请求
                const { data: res } = await this.$http.put(`categories/${this.editAttrForm.cat_id}/attributes/${this.editAttrForm.attr_id}`, {
                    attr_name: this.editAttrForm.attr_name,
                    attr_sel: this.activeName,
                    attr_vals: this.editAttrForm.attr_vals
                })
                // console.log(res);
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

                this.$message.success(res.meta.msg)
                // 隐藏修改分类的参数对话框
                this.editAttrDialogVisible = false
                // 重新请求商品分类列表数据（刷新列表）
                this.getParamsData()
            })
        },
        // 删除参数
        async removeParams(row) {
            // 弹窗用户是否要删除
            const confirmResult = await this.$confirm(`此操作将永久删除该${this.isTitle}, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            // 如果用户确认删除，则返回值为字符串 confirm
            // 如果用户取消了删除，则返回值为字符串 cancel
            if (confirmResult === 'confirm') {
                const { data: res } = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
                if (res.meta.status !== 200) return this.$message.error('删除失败！')
                this.$message.success('删除成功！')
                this.getParamsData()
            } else {
                this.$message.info('已取消删除')
            }
        },
        // 文本框失去焦点或按下了 Enter 键触发事件
        async handleInputConfirm(row) {
            if (row.inputValue.trim().length === 0) {
                row.inputValue = ''
                row.inputVisible = false
                return
            }
            // 如果没有 return 则需要后续处理
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = ''
            row.inputVisible = false

            // 需要发送请求
            const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: this.activeName,
                attr_vals: row.attr_vals.join(' ')
            })
            // console.log(res);
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

            this.$message.success(res.meta.msg)
        },
        // 点击按钮，展示文本框
        showInput(row) {
            row.inputVisible = true
            // 自动获取文本框焦点
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        // 删除属性参数
        async handleColose(row, index) {
            row.attr_vals.splice(index, 1)
            // 需要发送请求
            const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: this.activeName,
                attr_vals: row.attr_vals.join(' ')
            })
            // console.log(res);
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

            this.$message.success(res.meta.msg)

        }

    }
}
</script>

<style>
.el-row {
    margin: 15px 0;
}

.el-tag {
    margin: 10px;
}

.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>